import { Message } from 'element-ui'
import $ from 'jquery'
import router from '../router'

export default {
  _ajax: function(option) {
    var defer = $.Deferred()
    if (!option.type) option.type = 'POST'

    option.complete = function() {
      self.loading = true
    }
    option.error = function() {
      self.loading = false
    }
    var request = $.ajax(option)
    var promise = request.then(function(res) {
      if (res.errCode !== 0) {
        if (res.errCode === 20000) {
          Message({
            message: '登录超时，请重新登录！',
            type: 'error',
            duration: 2 * 1000
          })
          setTimeout(() => {
            sessionStorage.clear()
            router.push({ path: '/' })
          }, 2 * 1000)
        } else {
          Message({
            message: res.errMsg,
            type: 'error',
            duration: 3 * 1000
          })
        }
      } else {
        return res
      }
    }, function(response) {
      defer.reject()
    })
    promise.fail = function(response) {
      return defer.resolve()
    }
    promise.done = function(response) {
      defer = request = promise = null
    }
    return promise
  },
  _setUrl: function(url, params) {
    var qs = []
    if (params) {
      qs.push(url + '?')
      for (var k in params) {
        if (params[k]) {
          qs.push(k + '=' + params[k])
        }
      }
      return qs.join('&')
    } else {
      return url
    }
  },
  getData: function(url, params) {
    return this._ajax({
      type: 'GET',
      url: this._setUrl(url, params),
      dataType: 'json',
      xhrFields: {
        withCredentials: true
      },
      crossDomain: true
    })
  },
  postData: function(url, params) {
    return this._ajax({
      type: 'POST',
      url: url,
      xhrFields: {
        withCredentials: true
      },
      crossDomain: true,
      dataType: 'json',
      data: params
    })
  },
  postAsyncData: function(url, params) {
    return this._ajax({
      type: 'POST',
      url: url,
      xhrFields: {
        withCredentials: true
      },
      crossDomain: true,
      dataType: 'json',
      async: false,
      data: params
    })
  }
}
